package com.leessy.r229.server.http

import android.webkit.URLUtil
import com.leessy.r229.BuildConfig
import com.leessy.r229.constants.Constants
import com.leessy.r229.server.HttpApi
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.security.KeyStore
import java.util.Arrays
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
import kotlin.properties.Delegates

/**
 * @author : Created by liucheng. on 2021/01/04
 * @description : http server task synchronization request management
 */
object HttpRetrofit {
    private var retrofit: Retrofit? = null

    private var service: HttpApi by Delegates.notNull()

    fun apiService(): HttpApi {
//        retrofit?.let {
//            if (!it.baseUrl().url().toString().contains(Config.httpHost!!)) {
//                retrofit = null//服务地址变化更新
//            }
//        }
        if (retrofit == null) {
            service = getRetrofit()!!.create(HttpApi::class.java)
        }
        return service
    }


    private fun getRetrofit(): Retrofit? {
        if (retrofit == null) {
            synchronized(HttpRetrofit::class.java) {
                if (retrofit == null) {
                    var baseurl = Constants.BaseURL
                    if (!baseurl.endsWith("/")) {
                        baseurl = "$baseurl/"
                    }
                    //服务地址无效,初始化一个默认地址
                    if (!URLUtil.isValidUrl(baseurl)) {
                        baseurl = "http://192.168.1.1:12345/"
                    }
                    retrofit = Retrofit.Builder()
                        .baseUrl(baseurl)
                        .client(getOkHttpClient())
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                        .build()
                }
            }
        }
        return retrofit
    }

    /**
     * 获取 OkHttpClient
     */
    private fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient().newBuilder()
        /*ssl 新版方法*/
        val trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(null as KeyStore?)
        val trustManagers = trustManagerFactory.trustManagers
        check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
            "Unexpected default trust managers:" + Arrays.toString(trustManagers)
        }
        val trustManager = trustManagers[0] as X509TrustManager
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, arrayOf<TrustManager>(trustManager), null)
        val sslSocketFactory = sslContext.socketFactory

        return builder.run {
            addInterceptor(HeaderInterceptor())
            addInterceptor(HttpLoggingInterceptor().apply {
//                level = HttpLoggingInterceptor.Level.BODY
                if (BuildConfig.DEBUG)
//                    level = HttpLoggingInterceptor.Level.HEADERS
                    level = HttpLoggingInterceptor.Level.BODY
                else
                    level = HttpLoggingInterceptor.Level.HEADERS
            })
            addInterceptor(EncryptInterceptor())//body加密处理
            addInterceptor(DecryptInterceptor())//body加密处理
            connectTimeout(3, TimeUnit.SECONDS)
            readTimeout(4, TimeUnit.SECONDS)
            followRedirects(true)
            followSslRedirects(true)
            writeTimeout(4, TimeUnit.SECONDS)
            connectionPool(ConnectionPool(50, 5, TimeUnit.SECONDS))//连接保持时间太长，大量请求会卡死咯
            sslSocketFactory(sslSocketFactory, trustManager)//ssl
            retryOnConnectionFailure(true) // 错误重连
        }.build()
    }
}